# 分析结果数据-项目包类
# by lw 2023-11-05

import json


class Package():

    def __init__(self,
                 projectId: int = 0,
                 packageId: int = 0,
                 cunit: str = "",
                 cunitAddress: str = "",
                 amount: float = 0.00):
        """构造函数

        Args:
            projectId (int, optional): 项目标识码. Defaults to 0.
            packageId (int, optional): 包号. Defaults to 0.
            cunit (str, optional): 中标单位. Defaults to "".
            cunitAddress (str, optional): 中标单位地址. Defaults to "".
            amount (float, optional): 中标金额. Defaults to 0.00.
        """
        self.projectId = projectId  # 项目标识码
        self.packageId = packageId  # 包号
        self.cunit = cunit  # 中标单位
        self.cunitAddress = cunitAddress  # 中标单位地址
        self.amount = amount  # 中标金额

    def tostring(self) -> str:
        """将对象序列化为json字符串格式

        Returns:
            str: json字符串
        """
        return json.dumps(
            self,
            default=lambda obj: obj.__dict__,
            #   sort_keys=True,
            indent=2,
            ensure_ascii=False)

    def from_json(self, d: json) -> object:
        """对象反序列化:从json对象反序列化

        Args:
            d (json): Data_item类对象对应的json对象

        Returns:
            object: Data_item类对象self
        """
        self.projectId = d['projectId']
        self.packageId = d['packageId']
        self.cunit = d['cunit']
        self.cunitAddress = d['cunitAddress']
        self.amount = d['amount']
        return self

    def from_string(self, jstring: str) -> object:
        """对象反序列化：将描述的对象json字符串反序列化对象

        Args:
            jstring (str): 描述对象的json字符串

        Returns:
            object: Data_item类对象self
        """
        return json.loads(jstring, object_hook=self.from_json)


# 测试代码：
if __name__ == '__main__':
    # 不同的实例化：
    d = Package()
    print("无参数实例化的对象tostring:", d.tostring())
    d = Package(cunit="测试中标单位")
    print("有参数实例化的对象tostring:", d.tostring())
    # 反序列化
    j = json.loads(d.tostring())
    print("Json Object of package:", j)
    d2 = Package()
    d2.from_json(j)
    print("使用json对象实例化的对象tostring:", d2.tostring())
    d3 = Package()
    d3.from_string(d.tostring())
    print("使用json字符串实例化的对象tostring:", d3.tostring())
